package com.simba.server.commands.impl.fetch;

import java.sql.ResultSet;
import java.util.List;
import com.simba.common.command.ICommand;
import com.simba.common.database.DbOperator;
import com.simba.server.components.PrinterInfoManager;
import com.simba.server.components.data.PrinterInfo;
import com.simba.server.components.data.SlotInfo;

public class FetchSlotInfoCmd implements ICommand
{
	public static final String NAME = "FetchSlotInfoCmd";
	private final List<SlotInfo> slotInfos;
	private final String sql = "select * from tt_slot_config;";

	public FetchSlotInfoCmd(List<SlotInfo> slotInfos)
	{
		this.slotInfos = slotInfos;
	}

	@Override
	public String getName()
	{
		return FetchSlotInfoCmd.NAME;
	}

	@Override
	public Boolean run(Object params)
	{
		Boolean ret = false;

		if (!(params instanceof DbOperator))
		{
			return ret;
		}

		this.slotInfos.clear();

		try
		{
			DbOperator dbOperator = (DbOperator) params;

			dbOperator.prepareStatement(this.sql);

			ResultSet rs = dbOperator.executeQuery();

			while (rs.next())
			{
				SlotInfo slotInfo = new SlotInfo();

				String slotId = rs.getString("slotId");
				slotInfo.setSlotId(slotId);

				int slotDistrict = rs.getInt("slotDistrict");
				slotInfo.setSlotDistrict(slotDistrict);

				int slotWhetherUpload = rs.getInt("slotWhetherUpload");
				slotInfo.setSlotWhetherUpload(slotWhetherUpload);

				int sorterId = rs.getInt("sorterId");
				slotInfo.setSorterId(sorterId);

				String printerMasterId = rs.getString("masterPrinterId");
				PrinterInfo printerInfo = PrinterInfoManager.getInstance().getPrinterInfo(printerMasterId);
				if (printerInfo != null)
				{
					slotInfo.setMasterPrinterId(printerInfo.getPrinterId());
					slotInfo.setMasterPrinterIp(printerInfo.getPrinterIp());
				}

				String printerSlaveId = rs.getString("slavePrinterId");
				printerInfo = PrinterInfoManager.getInstance().getPrinterInfo(printerSlaveId);
				if (printerInfo != null)
				{
					slotInfo.setSlavePrinterId(printerInfo.getPrinterId());
					slotInfo.setSlavePrinterIp(printerInfo.getPrinterIp());
				}

				this.slotInfos.add(slotInfo);

				ret = true;
			}

		}
		catch (Exception ex)
		{
			ret = false;
		}

		return ret;
	}

}
